﻿using Abp;
using Abp.Application.Services;
using FwProject.Manager;
using FwProject.ShopApplication;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Abp.ObjectMapping;
using FwProject.ShoppingMall.EventAdvertising;
using Abp.Domain.Repositories;
using X.PagedList;
using System.Linq;
using AutoMapper.QueryableExtensions;
using FwProject.ShoppingMall.Com;
using FwProject.Com.Dto;
using Abp.AutoMapper;
using Microsoft.Extensions.Configuration;
using Microsoft.AspNetCore.Hosting;
using FwProject.PublicService;
using Abp.Authorization;

namespace FwProject.Com.Dto
{
    /// <summary>
    /// 广告位管理
    /// </summary>
    public class ShopAdAppService : FwProjectAppServiceBase, IShopAdAppService
    {
        private readonly ShopAdManager _shopAdManager;
        private readonly IRepository<ShopAd, Guid> _shopAdRepository;
        private readonly IRepository<ShopAdLocation, Guid> _shopAdLocationRepository;
        private Abp.IGuidGenerator _guid { get; set; }
        public IObjectMapper _map { get; set; }
        private readonly IConfigurationRoot _appConfiguration;

        /// <summary>
        /// 构造注入
        /// </summary>
        /// <param name="shopAdManager"></param>
        /// <param name="shopAdRepository"></param>
        public ShopAdAppService(ShopAdManager shopAdManager, IRepository<ShopAd, Guid> shopAdRepository, IRepository<ShopAdLocation, Guid> shopAdLocationRepository, IHostingEnvironment hostingEnvironment)
        {

            _shopAdManager = shopAdManager;
            _guid = SequentialGuidGenerator.Instance;
            _map = NullObjectMapper.Instance;
            _shopAdRepository = shopAdRepository;
            _shopAdLocationRepository = shopAdLocationRepository;

            _appConfiguration = hostingEnvironment.GetAppConfiguration();
           
        }
        /// <summary>
        /// 创建一个广告位
        /// </summary>
        /// <param name="Input">创建模型</param>
        /// <returns></returns>
        [AbpAuthorize]
        public async Task<Guid> CreateShopAdLocation(ShopAdInput Input)
        {
            var model = Input.MapTo<ShopAd>();
            model.Id = _guid.Create();

            string FileTempPath = _appConfiguration["FileServicePath:TempAdvertising"];
            string FileSavaPath = _appConfiguration["FileServicePath:SavaAdvertising:SavaFilePath"];
            var path = SaveFile(Input.PicLogo, FileTempPath, FileSavaPath, $"{DateTime.Now.ToString("yyyyMMdd")}/");
            model.PicLogo = _appConfiguration["FileServicePath:SavaAdvertising:Virtual"] + path;

            return await _shopAdManager.CreateShopAd(model);
        }
        /// <summary>
        /// 修改一个广告位
        /// </summary>
        /// <param name="Id">主键编号</param>
        /// <param name="Input">修改模型</param>
        /// <returns></returns>
        public async Task EditShopAdLocation(Guid Id, ShopAdInput Input)
        {
            var model = _shopAdRepository.Get(Id);
            var original = model.PicLogo;
            model = Input.MapTo(model);
            if (!Input.PicLogo.Contains("/uploads"))
            {
                var originalimg = original.Split('/');
                string FileTempPath = _appConfiguration["FileServicePath:TempAdvertising"];
                string FileSavaPath = _appConfiguration["FileServicePath:SavaAdvertising:SavaFilePath"];
                var path = SaveFile(Input.PicLogo, FileTempPath, FileSavaPath, $"{DateTime.Now.ToString("yyyyMMdd")}/", originalimg[originalimg.Length - 1]);
                model.PicLogo = _appConfiguration["FileServicePath:SavaAdvertising:Virtual"] + path;
            }
            await _shopAdManager.UpdateShopAd(model);
        }
        /// <summary>
        /// 删除一个广告位
        /// </summary>
        /// <param name="Id">主键编号</param>
        /// <returns></returns>
        public async Task DeleteAdLocation(Guid Id)
        {
            var model = _shopAdRepository.Get(Id);
            await _shopAdManager.DeleteShopAd(model);
        }
        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="page">页数</param>
        /// <param name="pageSize">条数</param>
        /// <param name="AdName">名称</param>
        /// <param name="beginTime">开始时间</param>
        /// <param name="endTime">结束时间</param>
        /// <param name="adTypeLocation">广告位</param>
        /// <param name="IsActive">是否激活</param>
        /// <returns></returns>
        public async Task<IPagedList<ShopAdDto>> GetPageList(int page, int pageSize, string AdName, DateTime? beginTime, DateTime? endTime, AdTypeLocation? adTypeLocation, bool? IsActive=true)
        {

            var list = _shopAdRepository.GetAllIncluding(o => o.ShopAdLocation);
            if (!string.IsNullOrEmpty(AdName))
                list = list.Where(o => o.AdName.Contains(AdName));

            if (adTypeLocation != null)
                list = list.Where(o => o.ShopAdLocation.AdTypeLocation == adTypeLocation);

            if (beginTime != null)
                list = list.Where(o => o.AdbeginTime >= beginTime);

            if (endTime != null)
                list = list.Where(o => o.AdEndTime <= endTime.Value.AddHours(24));


            if (IsActive != null)
                list = list.Where(o => o.IsActive == IsActive);

            return await list.Where(o=>o.AdEndTime>=DateTime.Now.AddHours(24)).OrderByDescending(o => o.CreationTime).ProjectTo<ShopAdDto>().ToPagedListAsync(page, pageSize);
        }

        #region 后台管理
        public async Task<ShopAdInput> GetEnterDtoAsync(Guid id)
        {
            var entity = await _shopAdRepository.GetAsync(id);
            return entity.MapTo<ShopAdInput>();
        }

        public async Task<LayerDataBaseDto> GetShopAdLayerDataAsync(int page, int limit, string keyword, Guid spaceid)
        {
            var query = _shopAdRepository.GetAll().Join(_shopAdLocationRepository.GetAll(), i => i.AdFlag, j => j.Id, (i, j) => new ShopAdOutputDto
            {
                Id = i.Id,
                AdFlag = i.AdFlag,
                AdbeginTime = i.AdbeginTime,
                AdEndTime = i.AdEndTime,
                AdFlagName = j.AdLocationTitle,
                AdName = i.AdName,
                AdType = i.AdType,
                IsActive = i.IsActive,
                CreationTime = i.CreationTime
            });
            if (!string.IsNullOrEmpty(keyword))
            {
                query = query.Where(o => o.AdName.Contains(keyword));
            }
            if (spaceid != Guid.Empty)
                query = query.Where(o => o.AdFlag == spaceid);


            var pagelist = await query.OrderByDescending(o => o.CreationTime).ToPagedListAsync(page, limit);

            LayerDataBaseDto dto = new LayerDataBaseDto();
            dto.Data = pagelist;
            dto.Count = pagelist.TotalItemCount;
            return dto;
        }

        public async Task SwitchActive(Guid id, bool active)
        {
            var entity = await _shopAdRepository.GetAsync(id);
            entity.IsActive = active;
            await _shopAdManager.UpdateShopAd(entity);
        }

        #endregion

    }
}
